﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using FaceRecognition.Models;
using FaceRecognition.Utilities;

namespace FaceRecognition.View
{
    public partial class Form_Login : Form
    {
        private Image img_default, img_user;
        private Face_Detection Obj_face_detection;
        private int pic_h, pic_w;
        int time_passed, seconds_allowed;
        bool face_detected = false;
        List<string> all_features;
        Controller_Class Obj_Controller;
        Face_Recognition Obj_Face_Recognition;
        double is_Him = 7000.0;
       
        public Form_Login()
        {
            all_features = new List<string>();

            Obj_face_detection = new Face_Detection();
            Obj_Controller = new Controller_Class();
            Obj_Face_Recognition = new Face_Recognition();
            InitializeComponent();
            pic_h = 128;
            pic_w = 128;
            img_user = null;
            time_passed = 0; seconds_allowed = 2000;
            try
            {

                img_default = Obj_face_detection.ResizeImage(Image.FromFile("..//admin.PNG"), new Size(pic_h, pic_w));
                pictureBox_main.Image = img_default;
                pictureBox_user.Image = img_default;
            }
            catch
            {
                MessageBox.Show("File not found  ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // Obj_face_detection.Close_Cam();

        }

        private void button_Notme_Click(object sender, EventArgs e)
        {
            pictureBox_user.Image = img_default;
            img_user = null;
            face_detected = false;
        }
        private void Time_Ended()
        {
            time_passed = 0;
            Obj_face_detection.Close_Cam();
            timer_Login.Stop();
            pictureBox_main.Image = img_default;
            //if (img_user == null)
            //{
            //    MessageBox.Show("We couldn't take the Picture  ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //}
            MessageBox.Show("You can't login try again ", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        private void timer_Login_Tick(object sender, EventArgs e)
        {
            // Obj_face_detection.Open_Camera();
            ///////////////////////////////////////////////////
            time_passed += timer_Login.Interval;
            label_time.Text = "" + ((int)(seconds_allowed - time_passed) / 1000);
            ////////////////////////////////////////////////////
            Image<Bgr, byte> displayed_frame = null;
            Obj_face_detection.Detect_Face(Obj_face_detection.Capture_Frame(), ref displayed_frame);
            if (displayed_frame == null)
            {
                pictureBox_main.Image = img_default;
            }
            else
                pictureBox_main.Image = Obj_face_detection.ResizeImage(displayed_frame.ToBitmap(), new Size((int)(pictureBox_main.Width * 1.1), (int)(pictureBox_main.Height * 1.1)));

            if (img_user == null)
                img_user = Obj_face_detection.Get_User_Face(new Size(pic_h, pic_w));

            if (img_user == null)// && !face_detected)
            {
                pictureBox_user.Image = img_default;
            }
            else //if (img_user != null && !face_detected)
            {
                pictureBox_user.Image = img_user;
                face_detected = true;
            }

            if (time_passed > seconds_allowed)
            {
                timer_Login.Enabled = false;
                Time_Ended();
            }
            ///////////////////////////////////////
            try_toLogin();

        }
        private void try_toLogin()
        {
            if (img_user == null)
                return;
            bool logged = false;
            double[] Str_UserMatch = Obj_Face_Recognition.Extract_Features(ImageOperations.Convert_Image(img_user));
            for (int i = 0; i < all_features.Count; i++)
            {
             
                    string[] temp_str = all_features[i].Split(',');
                    double[] arrDouble = new double[temp_str.Length];
                    for (int j = 0; j < temp_str.Length; j++)
                    {
                        arrDouble[j] = double.Parse(temp_str[j]);
                    }
                    double temp = Obj_Face_Recognition.Matching(arrDouble, Str_UserMatch);
                if (temp < is_Him)
                
                {
                    timer_Login.Stop();
                    MessageBox.Show(temp.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
                    logged = true;
                   
                    break;
                }
            }
            if (logged)
            {
                timer_Login.Stop();
                MessageBox.Show("You Logged in Successfully", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Singleton.Get_Instance();
                 if (all_features != null)
                  Singleton.Set_Info(textBox_Email.Text, all_features);
                 Obj_face_detection.Close_Cam();
                pictureBox_main.Image = img_default;
                Form_Session form_session = new Form_Session(this);
                form_session.Show();
                this.Hide();
                return;
            }
            img_user = null;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer_Login.Enabled = true;

        }

        private void button_Signup_Click(object sender, EventArgs e)
        {
            if (Obj_face_detection != null)
                Obj_face_detection.Close_Cam();
            timer_Login.Enabled = false;
            Form_AddUser form_adduser = new Form_AddUser();
            form_adduser.Show();
        }

        private void button_Login_Click(object sender, EventArgs e)
        {
           

            if (!General_Usage.isEmail(textBox_Email.Text))
            {
                MessageBox.Show("The email is not valid check it again", "Not valid", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                if (!Obj_Controller.User.email_exist(textBox_Email.Text))
                {
                    MessageBox.Show("The email is not exist", "Not exist", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show("Couldn't connect to Database", "DataBase Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            img_user = null;
            //if (img_user == null)
            //{
            //    MessageBox.Show("We didn't get your picture please click the Capture button", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            timer_Login.Enabled = true;
            //  int id=-1;

            try
            {
                all_features = Obj_Controller.retrive_feature_by_email(textBox_Email.Text);
               
                    //    id = Obj_Controller.retrive_id_by_email(textBox_Email.Text);
                   // all_features[i]=new double[temp_str.Length];
               //     all_features[i] = arrDouble;
                
            }
            catch
            {
                MessageBox.Show("Database Error ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }









            //take the picture and extract it's features
            //retrieve the id by email
            //get the features of that id
            //compare it with the database
            //if exist 
        }


    }
}
